package com.witdata.common.service.community.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.witdata.mysql.base.service.CommunityMemberBaseService;
import com.witdata.common.domain.Status;
import com.witdata.common.domain.dto.CommunityMemberDto;
import com.witdata.mysql.domain.entity.TCommunityMember;
import com.witdata.common.exception.GlobalException;
import com.witdata.common.service.community.MemberService;
import com.witdata.common.util.IdUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class MemberServiceImpl implements MemberService {
    private final CommunityMemberBaseService communityMemberBaseService;
    private final IdUtils idUtils;

    @Override
    public long getState(Long id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("community_id", id);
        return communityMemberBaseService.count(queryWrapper);
    }

    @Override
    public boolean checkWhetherToJoin(Long id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("community_id", id);
        queryWrapper.eq("user_id", idUtils.getUserIdByRequest());
        return communityMemberBaseService.exists(queryWrapper);
    }

    @Override
    public void addMember(Long communityId, Long memberId) {
        TCommunityMember tCommunityMember = TCommunityMember.builder()
                .id(IdUtils.createId())
                .communityId(communityId)
                .userId(memberId)
                .joinDate(LocalDateTime.now())
                .build();
        boolean save = communityMemberBaseService.save(tCommunityMember);
        if (!save) throw new GlobalException(Status.JoinError);
    }

    @Override
    public void joinCommunity(CommunityMemberDto communityMemberDto) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("community_id", communityMemberDto.getCommunityId());
        queryWrapper.eq("user_id", communityMemberDto.getUserId());
        boolean exists = communityMemberBaseService.exists(queryWrapper);
        if (exists) throw new GlobalException(Status.AlreadyJoined);
        addMember(communityMemberDto.getCommunityId(), communityMemberDto.getUserId());
    }

    @Override
    public void leaveCommunity(CommunityMemberDto communityMemberDto) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("community_id", communityMemberDto.getCommunityId());
        queryWrapper.eq("user_id", communityMemberDto.getUserId());
        boolean exists = communityMemberBaseService.exists(queryWrapper);
        if (!exists) throw new GlobalException(Status.NotJoin);
        boolean remove = communityMemberBaseService.remove(queryWrapper);
        if (!remove) throw new GlobalException(Status.LeaveError);
    }
}
